<?php
namespace application\datatypes;
use application\datatypes\DataType;
abstract class FileUploadBase extends Datatype {
	
	protected $approvedExtensions = array();
	
	public static function validate($field, $data, $results) {
		$aux = $field->cf_aux;
		$params = explode(',', $aux);
		if(count($params)) {
			$minimum = $params[0];
			$maximum = $params[1];
		}
		if($field->cf_required && !$data[$field->cf_column]) {
			$results['errors'][] = '<b>'.$field->cf_display_name.'</b> is required.';
		}
		if($minimum && count($data[$field->cf_column]) < $minimum) {
			if($minimum == 1)
				$results['errors'][] = '<b>'.$field->cf_display_name.'</b> must have at least 1 file.';
			else
				$results['errors'][] = '<b>'.$field->cf_display_name.'</b> must have at least '.$minimum.' files.';
		}
		elseif($maximum && count($data[$field->cf_column]) > $maximum) {
			$results['errors'][] = '<b>'.$field->cf_display_name.'</b> - You are only allowed to upload '.$maximum.' files.';
		}
		
		elseif($value = $data[$field->cf_column]) {
			// Parse all uploads and add field, content comes later
			if(count($value)) {
				$files = "'".implode("', '", $value)."'";
				DB()->query("UPDATE `cn_uploads` SET `upload_field`='$field->cf_id' WHERE `upload_id` IN ($files)");
			}
			$results['db_fields']['files_'.$field->cf_column] = $value;
			
			
		}
		return $results;
	}
	
	public static function endForm($field, $data, $id, $type) {
		$files = $data['files_'.$field->cf_column];
		DB()->query("UPDATE `cn_uploads` SET `upload_content`='0' WHERE `upload_content` = '$id' AND `upload_field`='$field->cf_id'");
		if(count($files)) {
			$i = 1;
			foreach($files as $file) {
				DB()->query("UPDATE `cn_uploads` SET `upload_content`='$id', `upload_order`='$i' WHERE `upload_id`='$file'");
				$i++;
			}
		}
		
	}
	
	public static function display($formElements) {
		?>
		
		<fieldset class="single-field">
			<header><?=$formElements['display']?></header>
			<section class="inner">
			<?php if($description = $formElements['description']) : ?>
				<p class="form-description"><?=$description?></p>
			<?php endif;?>
			<?php if(count($formElements['elements']['existing'])) : ?>
			<script type="text/javascript">
				$(document).ready(function() {
					<?php foreach($formElements['elements']['existing'] as $existing) : ?>
					$('#<?=$formElements['column']?>_uploader').uploader('add_file', {location:'uploads/<?=$existing->upload_filename?>', id:<?=$existing->upload_id?>});
					<?php endforeach;?>
				});
			</script>
			<?php endif;?>
			
			<?=$formElements['elements']['element']?>
			</section>
		</fieldset>
		<?php
	}
	
	public static function fromDB($fields, $field, $data) {
		$column = $field->cf_column;
		
		$id = $data['content_id'];
		if($id) {
		// Get tags from DB
			$files = DB()->getVarArray("SELECT `upload_id` FROM `cn_uploads` WHERE `upload_field`='$field->cf_id' AND `upload_content`='$id' ORDER BY `upload_id`");
		}
		else {
			$files = array();
		}	
		return array($field->cf_column => $files);
	}
	
	public static function uploadJS($field) {
		Modulator()->includeScript('jquery');
		$class = 'application\\datatypes\\' . $field->cf_data_type;
		Modulator()->includeScript(getCommonFile('concerto/app-dev-suite/uploader/uploader.js'));
		$aux = $field->cf_aux;
		$params = explode(',', $aux);
		if(count($params)) {
			$minimum = $params[0];
			$maximum = $params[1];
		}
		?>
		<link href="<?=getCommonFile('concerto/app-dev-suite/uploader/uploader.css')?>" rel="stylesheet" type="text/css" />
		<script type="text/javascript">
			$(document).ready(function() {
				$('#<?=strtolower($field->cf_column)?>_uploader').uploader({
					uploadHandler:'<?=CN_URL?>?view=handler&handler=file-upload',
					validTypes:[
						<?=$class::$filters?>
					],
					onUploadCompleted:function(data, file) {
						console.log(data);
						file.li.append('<input type="hidden" name="<?=$field->cf_column?>[]" value="' + data.id + '"/>');
						<?php $class::onUpload($field);?>
					}
				});
				

			});
		</script>
		<?php

	}
	
	public static function build($field, $data) {
		$files = $data[$field->cf_column];
		$class = 'uploader-'.strtolower($field->cf_column);
		$dataType = 'application\\datatypes\\' . $field->cf_data_type;
		$input = array();
		$existing = array();
		if(is_array($files)) {
			foreach($files as $file) {
				// Get file name
				$file = DB()->getRow("SELECT `upload_filename`, `upload_id` FROM `cn_uploads` WHERE `upload_id`='$file'");
				$existing[] = $file;
			}
		}
		
		$formElements = array('description'=>$field->cf_description, 'column'=>$field->cf_column, 'display'=>$field->cf_display_name, 'data_type'=>$field->cf_data_type, 'elements'=>array(
				'existing'=>$existing,
				'element'=>
					sprintf('<input id="%s" type="file" class="%s"></div>',  ($field->cf_column.'_uploader'), $class)
				));
		return $formElements;
	
	}
	
	public static function editForm($field) {
		?>
			<ul class="form-fields">
			<input type="hidden" name="field_id" value="<?=$field->getId()?>"/>
			<li>
			<label>Field Display Name</label>
			<input type="text" name="field_display_name" class="big wide" value="<?=$field->getDisplayName()?>"/>
			</li>
			<li>
			<label>Field Description</label>
			<textarea name="field_description" class="wide"><?=$field->getDescription()?></textarea>
			</li>
			<li>
				<?php 
					$aux = $field->getAux();
					$params = explode(',', $aux);
					if(count($params)) {
						$minimum = $params[0];
						$maximum = $params[1];
					}
				?>
				
				<label>Minimum</label><input type="text" name="minimum_files" value="<?=$minimum?>" class="thin"/>
				<label>Maximum</label><input type="text" name="maximum_files" value="<?=$maximum?>" class="thin"/>
			</li>
			<li>
				<label><input type="checkbox" name="field_required" <?=($field->getRequired()) ? 'checked="checked"' : ''?> value="1"/> Required</label>
				<label><input type="checkbox" name="field_show" value="1" <?=($field->getShow()) ? 'checked="checked"' : ''?>/> Show in Manage Panel</label>
				
			</li>
			

			</ul>
			</form>
			<?php
	}
	
	public static function save() {
		$max = $_REQUEST['maximum_files'];
		$min = $_REQUEST['minimum_files'];
		$join = $min.','.$max;
		$field = $_REQUEST['field'];
		DB()->query("UPDATE `cn_content_fields` SET `cf_aux`='$join' WHERE `cf_id`='$field'");
	}
	
}
?>